package flca.projbuilder.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.codehaus.jackson.map.ObjectMapper;

import com.google.common.io.Files;

import flca.projbuilder.ProjBuilderConstants;
import flca.projbuilder.dto.TemplateDto;

public class TemplateDtoHelper implements ProjBuilderConstants {

	public static Set<TemplateDto> findAllTemplates() {
		Set<TemplateDto>  r = new HashSet<>();
		ObjectMapper mapper = new ObjectMapper();
		
		for (File f : findJsonFiles(templatesDir())) {
			try {
				TemplateDto td = mapper.readValue(new File(f.getPath()), TemplateDto.class);
				File zipfile = getZipFile(f);
				if (zipfile.exists()) {
					td.setZipSource(getZipFile(f));
					td.setName(name(f));
					r.add(td);
				} else {
					System.out.println("zipSource " + td.getZipSource() + " does not exist");
					System.out.println("You should have a zipfile with the same name as the .json file in the \templates folder!");
				}
			} catch (Exception e) {
				System.out.println("error parsing " + f.getName() +  " :" + e);
			}			
		}
		return r;
	}
	
	private static File getZipFile(File aFile) {
		return new File(templatesDir() + "/" + name(aFile) + ".zip");
	}
	
	private static String name(File aFile) {
		return Files.getNameWithoutExtension(aFile.getName());
	}
	
	private static String templatesDir() {
		return getCurrentDir() + "/" + TEMPLATE_DIR;
	}
	
	private static List<File> findJsonFiles(String aSeachRootDir) {
		
		List<File> r = new ArrayList<>();
		File f = new File(aSeachRootDir);
		File files[] = f.listFiles();

		if (files != null) {
			for (File file : files) {
				if (file.getPath().endsWith(TEMPLATE_EXT)) {
					r.add(file);
				}
			}
		}
		
		return r;
	}
	
	public static String getCurrentDir() {
		try {
			return new File(".").getCanonicalPath();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}	
}
